package com.synjones.handsetS8.ild.pages;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.synjones.handsetS8.R;;
import com.synjones.handsetS8.Utils.util;
import com.synjones.handsetS8.ild.adapter.OnItemChildViewClickListener;
import com.synjones.handsetS8.ild.adapter.WorkerRvAdapter;
import com.synjones.handsetS8.ild.base.BaseRecyclerAdapter;
import com.synjones.handsetS8.ild.constants.RequestCodes;
import com.synjones.handsetS8.ild.net.api.RosterApi;
import com.synjones.handsetS8.ild.net.common.NetCallback;
import com.synjones.handsetS8.ild.net.common.NetResponse;
import com.synjones.handsetS8.ild.net.model.ListResult;
import com.synjones.handsetS8.ild.net.model.NetResult;
import com.synjones.handsetS8.ild.net.model.SensorInfo;
import com.synjones.handsetS8.ild.net.model.WorkerResult;
import com.synjones.handsetS8.ild.pages.select.SelectActivity;
import com.synjones.handsetS8.ild.popup.ChangeBraceletWindow;
import com.synjones.m1card.M1CardInfo;
import com.synjones.reader.IDCardReaderModule;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 工人列表
 */
public class WorkerListActivity extends AppCompatActivity implements View.OnClickListener,
        DatePickerDialog.OnDateSetListener,
        BaseRecyclerAdapter.OnItemClickListener<WorkerResult>,
        OnItemChildViewClickListener<WorkerResult> {
    private View root;
    private ImageView ivBack;
    private ImageView ivDate;
    private TextView tvTitle;
    private TextView tvTeam;
    private EditText etWorkerName;
    private RecyclerView rvWorker;

    private WorkerRvAdapter adapter;
    private List<WorkerResult> workerInfoList = new ArrayList<>();

    private ImageView ivSearch;
    private PopupWindow popupWindowChange;
    private PopupWindow popupWindowQuit;
    private ChangeBraceletWindow changeBraceletWindow;
    private String workerId;
    private String braceletNo;

    private int sensorStatus = 0;

    //搜索参数
    private Long teamId;
    private String name;
    private Long startDate;
    private Long endDate;
    private long page = 0;
    private long size = 10;

    private boolean pickedStart;// 标记 是否已选择了开始时间

    //手环
    IDCardReaderModule idCardReaderModule;
    boolean isConnect;
    final int MESSAGE_FIND_CARD = 0x51;
    boolean findingCard = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        root = getLayoutInflater().inflate(R.layout.act_worker_list, null);
        setContentView(root);

        init();
    }

    private void init() {
        //关闭键盘自动弹出
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        tvTitle = (TextView) findViewById(R.id.tv_title);

        tvTitle.setText("花名册");

        idCardReaderModule = IDCardReaderModule.getInstance(this);
        isConnect = idCardReaderModule.isOpen();

        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);

        ivDate = (ImageView) findViewById(R.id.iv_option);
        ivDate.setVisibility(View.VISIBLE);
        ivDate.setOnClickListener(this);

        tvTeam = (TextView) findViewById(R.id.tv_team);
        tvTeam.setOnClickListener(this);

        etWorkerName = (EditText) findViewById(R.id.et_worker_name);

        ivSearch = (ImageView) findViewById(R.id.iv_search);
        ivSearch.setOnClickListener(this);

        rvWorker = (RecyclerView) findViewById(R.id.rv_worker);

        adapter = new WorkerRvAdapter(this, workerInfoList);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemChildViewClickListener(this);

        rvWorker.setLayoutManager(new LinearLayoutManager(this));
        rvWorker.setAdapter(adapter);


        changeBraceletWindow = new ChangeBraceletWindow(this, getLayoutInflater().inflate(R.layout.pop_worker_change_bracelet, null), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        initQuitConfirmWindow();
        initChangeBraceletWindow();

        getWorkerListData(null, null, null, null, page, size);
    }

    /**
     * 获取工人列表数据
     */
    private void getWorkerListData(String name, Long teamId, Long startTime, Long endTime, long page, long size) {
        RosterApi.getWorkerList(name, teamId, startTime, endTime, page, size, new NetCallback<NetResult<ListResult<WorkerResult>>>() {
            @Override
            protected void onComplete(NetResponse<NetResult<ListResult<WorkerResult>>> netResponse) {
                if (netResponse.isSuccess) {
                    workerInfoList = netResponse.data.getData().getList();
                    adapter.updateData(workerInfoList);
                    Toast.makeText(WorkerListActivity.this, "数据刷新成功", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 更换手环窗口
     */
    private void initChangeBraceletWindow() {
        View contentView = getLayoutInflater().inflate(R.layout.pop_worker_change_bracelet, null);
        popupWindowChange = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindowChange.setOutsideTouchable(true);
        TextView tvOk = contentView.findViewById(R.id.btn_ok);
        TextView tvBraceletNo = contentView.findViewById(R.id.tv_bracelet_no);
        contentView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowChange.dismiss();
            }
        });

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String braceleNo = tvBraceletNo.getText().toString().trim();
                RosterApi.changeBracelet(workerId, braceleNo, new NetCallback<NetResult>() {
                    @Override
                    protected void onComplete(NetResponse<NetResult> netResponse) {
                        if (netResponse.isSuccess) {
                            Toast.makeText(WorkerListActivity.this, "更换手环成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(WorkerListActivity.this, "更换手环未成功", Toast.LENGTH_SHORT).show();
                        }
                        popupWindowChange.dismiss();
                        getWorkerListData(etWorkerName.getText().toString().trim(), teamId, startDate, endDate, page, size);
                    }
                });
            }
        });
    }

    /**
     * 退工确认窗口
     */
    private void initQuitConfirmWindow() {
        View contentView = getLayoutInflater().inflate(R.layout.pop_worker_quit, null);
        popupWindowQuit = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindowQuit.setOutsideTouchable(true);
        TextView tvOk = contentView.findViewById(R.id.btn_quit_ok);
        Switch swtBracelet = contentView.findViewById(R.id.swt_bracelet);
        contentView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowQuit.dismiss();
            }
        });

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RosterApi.retire(workerId, swtBracelet.isChecked() ? 1 : 0, new NetCallback<NetResult>() {
                    @Override
                    protected void onComplete(NetResponse<NetResult> netResponse) {
                        if (netResponse.isSuccess) {
                            Toast.makeText(WorkerListActivity.this, "退工成功", Toast.LENGTH_SHORT).show();
                            popupWindowQuit.dismiss();
                            getWorkerListData(etWorkerName.getText().toString().trim(), teamId, startDate, endDate, page, size);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.iv_back:
                finish();
                return;
            //拾取进场日期范围
            case R.id.iv_option:
                pickIntoDateRange();
                return;
            //拾取班组
            case R.id.tv_team:
                selectLaborAndTeam();
                return;
            //搜索
            case R.id.iv_search:
                page = 0;
                search();
                return;
            default:
                break;
        }
    }

    /**
     * 连续拾取分包单位和班组
     */
    private void selectLaborAndTeam() {
        toSelect("选择分包单位", RequestCodes.SELECT_UNIT, 0, null);
    }

    /**
     * 搜索
     */
    private void search() {
        getWorkerListData(etWorkerName.getText().toString().trim(), teamId, startDate, endDate, page, size);
    }

    private void pickIntoDateRange() {
        pickedStart = false;
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        pickDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * 拾取日期
     */
    private void pickDate(int year, int month, int dayOfMonth) {
        //构建一个日期对话框，该对话框已经集成了日期选择器
        //DatePickerDialog的第二个构造参数指定了日期监听器
        DatePickerDialog dialog = new DatePickerDialog(this, this, year, month, dayOfMonth);
        //把日期对话框显示在界面上
        dialog.show();
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        //如果开始时间已经被拾取，则处理为结束时间
        Date date = new Date(year - 1900, month, dayOfMonth);
        if (pickedStart) {
            endDate = date.getTime() / 1000;
            System.out.println("endDate: " + startDate);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            String info = sdf.format(startDate * 1000) + " - " + sdf.format(endDate * 1000);
            Toast.makeText(this, info, Toast.LENGTH_SHORT).show();
        } else {
            //否则就是开始时间了
            startDate = date.getTime() / 1000;
            System.out.println("startDate: " + startDate);
            //继续拾取结束日期
            pickedStart = true;
            pickDate(year, month, dayOfMonth);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                //选择分包单位
                case RequestCodes.SELECT_UNIT:
                    long laborId = data.getLongExtra("select_item_id", 0);
                    toSelect("选择班组", RequestCodes.SELECT_TEAM, 1, laborId);
                    break;
                //选择班组
                case RequestCodes.SELECT_TEAM:
                    tvTeam.setText(data.getStringExtra("select_item_name"));
                    teamId = data.getLongExtra("select_item_id", 0);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 到选择页面
     *
     * @param title
     * @param requestCode
     * @param laborId
     */
    private void toSelect(String title, int requestCode, int dataType, Long laborId) {
        Intent intent = new Intent(this, SelectActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("data_type", dataType);
        if (dataType == 1) {
            intent.putExtra("labor_id", laborId);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 列表项点击回调
     *
     * @param tag
     * @param itemView
     * @param position
     * @param item
     */
    @Override
    public void onItemClick(String tag, View itemView, int position, WorkerResult item) {
    }

    /**
     * 列表项子控件点击回调
     *
     * @param view
     * @param itemView
     * @param position
     * @param itemData
     */
    @Override
    public void onChildViewClick(View view, View itemView, int position, WorkerResult itemData) {
        workerId = itemData.getWorker_id();
        if (view.getId() == R.id.btn_change) {
            //弹框然后调用接口
            resetPopBraceletTips();
            popupWindowChange.showAtLocation(root, Gravity.CENTER, 0, 0);
            FindCard(5000);
        }
        if (view.getId() == R.id.btn_quit) {
            SensorInfo sensorInfo = itemData.getSensorInfo();
            if (null == sensorInfo) {
                sensorStatus = 0;
            } else {
                if (sensorInfo.getOwner_type() == 3) {
                    sensorStatus = 2;//自带
                } else {
                    sensorStatus = 1;//已发放
                }
            }
            //弹框读取设备 然后调用接口
            View llBraContainer = popupWindowQuit.getContentView().findViewById(R.id.ll_bra_container);
            if (sensorStatus != 1) {
                llBraContainer.setVisibility(View.GONE);
            }else{
                llBraContainer.setVisibility(View.VISIBLE);
            }
            popupWindowQuit.showAtLocation(root, Gravity.CENTER, 0, 0);
        }

        LinearLayout llOP = itemView.findViewById(R.id.ll_op);
        llOP.setVisibility(View.GONE);
    }

    private void resetPopBraceletTips() {
        ((TextView) popupWindowChange.getContentView().findViewById(R.id.tv_bracelet_no)).setText("请扫描手环RFID");
    }

    /**
     * 读取手环的结果
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (MESSAGE_FIND_CARD == msg.what) {
                M1CardInfo m1CardInfo = (M1CardInfo) msg.obj;
                if (m1CardInfo != null) {
                    String braceletCode = m1CardInfo.getCardNoStr();
                    ((TextView) popupWindowChange.getContentView().findViewById(R.id.tv_bracelet_no)).setText(braceletCode);
                    Toast.makeText(WorkerListActivity.this, "已探测到手环", Toast.LENGTH_SHORT).show();
                    //popupWindowChange.dismiss();
                }
            }
        }
    };

    /**
     * 寻卡
     */
    public void FindCard(final int timeout) {
        findingCard = true;
        new Thread(new Runnable() {

            @Override
            public void run() {
                M1CardInfo m1CardInfo = null;
                long t = System.currentTimeMillis();
                while (findingCard && System.currentTimeMillis() - t < timeout && m1CardInfo == null) {
                    m1CardInfo = idCardReaderModule.findM1Card();
                    if (m1CardInfo != null) {
                        mHandler.obtainMessage(MESSAGE_FIND_CARD, m1CardInfo).sendToTarget();
                        break;
                    }
                    util.sleep(50);
                }
                findingCard = false;
                if (m1CardInfo == null)
                    mHandler.obtainMessage(MESSAGE_FIND_CARD, null).sendToTarget();

            }
        }).start();
    }
}